package win.doyto.service.data.report;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.View;
import win.doyto.service.data.config.ReportConfigApi;
import win.doyto.service.data.config.ReportConfigEntity;
import win.doyto.service.data.exception.ResourceNotFoundException;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;


/**
 * DataReportController
 *
 * @author f0rb on 2017-12-20.
 */
@Slf4j
@Controller
@RequestMapping("/report")
public class ReportController {

    public static final String KEY_REPORT_CONFIG_LIST = "report";
    public static final String KEY_PARAMS = "params";
    public static final String KEY_SUFFIX = "suffix";
    public static final String KEY_TITLE = "title";

    @Resource
    private ReportConfigApi reportConfigApi;

    @SuppressWarnings("unchecked")
    @GetMapping("{report:.+}")
    public View report(Model model, @PathVariable("report") String report, String data, String title) {
        Map<String, Object> param;

        if (StringUtils.isNotBlank(data)) {
            param = JSON.parseObject(data, Map.class);
        } else {
            param = new HashMap<>();
        }
        return report(model, report, param, title);
    }

    @PostMapping("{report:.+}")
    public View report(
            Model model, @PathVariable("report") String report,
            @RequestBody Map<String, Object> data, String title
    ) {
        int dotIndex = report.lastIndexOf('.');
        String reportKey = report;
        String suffix = "";
        if (dotIndex > 0) {
            reportKey = report.substring(0, dotIndex);
            suffix = report.substring(dotIndex + 1);
        }

        Collection<ReportConfigEntity> reportConfigEntities = reportConfigApi.findByReportKey(reportKey);
        if (reportConfigEntities.isEmpty()) {
            throw new ResourceNotFoundException();
        }

        model.addAttribute(KEY_REPORT_CONFIG_LIST, new ArrayList<>(reportConfigEntities));
        model.addAttribute(KEY_SUFFIX, suffix);
        model.addAttribute(KEY_PARAMS, data);
        model.addAttribute(KEY_TITLE, title);

        View view = AbstractReportView.chooseViewBySuffix(suffix);
        if (view == null) {
            view = AbstractReportView.chooseViewBySuffix("json");
        }
        return view;
    }

}
